package com.source.baseData.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.source.baseData.entity.District;
import com.source.baseData.entity.SlaughterHouse;
import com.source.baseData.entity.Stalls;
import com.source.baseData.entity.ToMarket;
import com.source.baseData.service.DistrictService;
import com.source.baseData.service.SlaughterHouseService;
import com.source.baseData.vo.SlaughterHouseAddressVo;
import com.source.baseData.vo.SlaughterHouseMapVo;
import com.source.labelAndBarcode.vo.SlaughterHouseVo;
import com.source.labelAndBarcode.vo.StallsVo;
import com.source.savings.Saving;
import com.source.sys.service.UserService;
import com.source.utils.CommonResult;
import com.source.utils.DistrictBuilder;
import com.source.utils.ExcelUtil;
import com.source.utils.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Joey
 * @since 2021-02-10
 */
@Api(tags = "屠宰场基础数据管理")
@RestController
@CrossOrigin
@RequestMapping("/baseData/slaughter-house")
public class SlaughterHouseController {

    @Autowired
    SlaughterHouseService slaughterHouseService;

    @Autowired
    UserService userService;

    @Autowired
    DistrictService districtService;

    @Autowired
    DistrictBuilder districtBuilder;

    @ApiOperation(value = "下载excel")
    @GetMapping(value = "/downloadExcel", produces = "application/vnd.ms-excel;charset=utf-8")
    public CommonResult<String> downloadExcel(HttpServletResponse response) throws IOException {
        List<SlaughterHouseVo> allVo = slaughterHouseService.findAllVo();
        ExcelUtil.downloadExcel(response, SlaughterHouseVo.class, allVo);
        return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
    }

    @ApiOperation(value = "上传Excel，存储数据到数据库中")
    @PostMapping(value = "/uploadExcel", produces = "application/json;charset=utf-8")
    public CommonResult<String> uploadExcel(@RequestPart(value = "excelFile", required = false) MultipartFile excelFile) throws IOException {
        if (null != excelFile && !excelFile.isEmpty()) {
            ExcelUtil.uploadExcel(excelFile, SlaughterHouse.class, slaughterHouseService);
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }


    @ApiOperation(value = "增加一个屠宰场，等待管理员审核")
    @PostMapping("/saveSlaughterHouse")
    public CommonResult<String> requestForSaveSlaughterHouse(@RequestBody @Validated SlaughterHouse slaughterHouse) {
        slaughterHouse.setStatus(2);
        String provinceId = slaughterHouse.getProvince();
        String cityId = slaughterHouse.getCity();
        String districtId = slaughterHouse.getDistrict();

        Map<String, String> pcdName = districtBuilder.getPCDName(provinceId, cityId, districtId);
        slaughterHouse.setProvince(pcdName.get("province"));
        slaughterHouse.setCity(pcdName.get("city"));
        slaughterHouse.setDistrict(pcdName.get("district"));

        if (slaughterHouseService.save(slaughterHouse)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @Deprecated
    @ApiOperation(value = "带图片上传的保存功能，相当于insert（测试版本）")
    @PostMapping(value = "/saveSHImage")
    public CommonResult<String> saveImage(@ModelAttribute @Validated SlaughterHouse sh,
                                          @RequestPart(required = false) MultipartFile image,
                                          HttpServletRequest request) throws Exception {
        if (null == image) {
            return requestForSaveSlaughterHouse(sh);
        }
        int i = slaughterHouseService.saveImage(sh, image, request);
        if (i != 0) {
            return new CommonResult<String>(ResultEnum.SUCCESS);
        }
        return new CommonResult<String>(ResultEnum.ERROR);
    }


    @ApiOperation("管理员审核，根据id批量通过发布请求")
    @PostMapping("/permissionForSaving/{ids}")
    public CommonResult<String> permissionForSavingByIds(@PathVariable(value = "ids") List<String> ids) {
        QueryWrapper<SlaughterHouse> wrapper = new QueryWrapper<SlaughterHouse>();
        List<SlaughterHouse> slaughterHouses = slaughterHouseService.list(wrapper.in("slaughterHouseId", ids));
        for (SlaughterHouse slaughterHouse : slaughterHouses) {
            slaughterHouse.setStatus(1);
        }
        if (slaughterHouseService.saveOrUpdateBatch(slaughterHouses)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }


    @ApiOperation("根据id删除数据，等待管理员审核")
    @DeleteMapping("/requestForDeletingById/{id}")
    public CommonResult<String> requestForDeletingById(@PathVariable(value = "id") String id) {
        QueryWrapper<SlaughterHouse> wrapper = new QueryWrapper<SlaughterHouse>();
        wrapper.eq("slaughterHouseId", id);
        SlaughterHouse slaughterHouse = slaughterHouseService.getOne(wrapper);
        slaughterHouse.setStatus(3);
        if (slaughterHouseService.saveOrUpdate(slaughterHouse)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @Deprecated
    @ApiOperation("根据id批量删除数据，等待管理员审核")
    @DeleteMapping("/requestForDeletingByIds/{ids}")
    public CommonResult<String> requestForDeletingByIds(@PathVariable(value = "ids") List<String> ids) {
        QueryWrapper<SlaughterHouse> wrapper = new QueryWrapper<SlaughterHouse>();
        List<SlaughterHouse> slaughterHouses = slaughterHouseService.list(wrapper.in("slaughterHouseId", ids));
        for (SlaughterHouse slaughterHouse : slaughterHouses) {
            slaughterHouse.setStatus(3);
        }
        if (slaughterHouseService.saveOrUpdateBatch(slaughterHouses)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @Deprecated
    @ApiOperation("管理员审核，根据id批量通过删除请求")
    @DeleteMapping("/permissionForDeletingByIds/{ids}")
    public CommonResult<String> permissionForDeletingByIds(@PathVariable(value = "ids") List<String> ids) {
        QueryWrapper<SlaughterHouse> wrapper = new QueryWrapper<SlaughterHouse>();
        List<SlaughterHouse> slaughterHouses = slaughterHouseService.list(wrapper.in("slaughterHouseId", ids));
        for (SlaughterHouse slaughterHouse : slaughterHouses) {
            slaughterHouse.setStatus(0);
        }
        if (slaughterHouseService.saveOrUpdateBatch(slaughterHouses) && slaughterHouseService.removeByIds(ids)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }

    @ApiOperation(value = "管理员审核（审核通过） ", notes = "，传id")
    @PostMapping(value = "/confirm/{id}")
    public CommonResult<String> confirm(@PathVariable String id) {
        SlaughterHouse byId = slaughterHouseService.getById(id);
        try {
            if(byId.getStatus() == 3){
                byId.setStatus(0);
                if (slaughterHouseService.updateById(byId) && slaughterHouseService.removeById(id)) {
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            }else if(byId.getStatus() == 2) {
                byId.setStatus(1);
                if(slaughterHouseService.updateById(byId)){
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            } else {
                return new CommonResult<String>(ResultEnum.ERROR, "该数据不处于待删除或待通过状态！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }

    @ApiOperation(value = "管理员审核（审核不通过） ", notes = "单个审核，传id，如果是待删除状态，执行后会恢复正常\n如果是待发布状态，执行后会删除数据")
    @PostMapping(value = "/disConfirm/{id}")
    public CommonResult<String> disConfirm(@PathVariable String id) {
        SlaughterHouse byId = slaughterHouseService.getById(id);
        try {
            if(byId.getStatus() == 3){
                byId.setStatus(1);
                if (slaughterHouseService.updateById(byId)) {
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            }else if(byId.getStatus() == 2) {
                byId.setStatus(0);
                if(slaughterHouseService.updateById(byId) && slaughterHouseService.removeById(id)){
                    return new CommonResult<String>(ResultEnum.SUCCESS);
                } else {
                    return new CommonResult<String>(ResultEnum.ERROR);
                }
            } else {
                return new CommonResult<String>(ResultEnum.ERROR, "该数据不处于待删除或待通过状态！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<String>(ResultEnum.ERROR, "操作异常！");
        }
    }



    @ApiOperation("根据id修改数据，主键id不可修改")
    @PutMapping("/updateById")
    public CommonResult<String> updateById(@RequestBody SlaughterHouse slaughterHouse) {
        if (slaughterHouseService.updateById(slaughterHouse)) {
            return new CommonResult<String>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
        }
        return new CommonResult<String>(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMsg());
    }


    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部数据")
    public CommonResult<List<SlaughterHouseVo>> findAll() {
        List<SlaughterHouseVo> list = slaughterHouseService.findAllVo();
        return new CommonResult<List<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @Deprecated
    @GetMapping("/findAllOnPagination")
    @ApiOperation(value = "查询全部数据", notes = "分页，且无关屠宰场状态")
    public CommonResult<IPage<SlaughterHouseVo>> findAllOnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                     @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> housePage = slaughterHouseService.findAllOnPagination(page);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), housePage);
    }

    @GetMapping("/findByUnChecked")
    @ApiOperation(value = "查询待审核的数据", notes = "分页")
    public CommonResult<IPage<SlaughterHouseVo>> findByUnChecked(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                 @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> houseVoIPage = slaughterHouseService.findByUnChecked(page);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS, houseVoIPage);
    }

    @GetMapping("/findByUnCheckedAndKeyWord")
    @ApiOperation(value = "模糊查询待审核的数据", notes = "分页")
    public CommonResult<IPage<SlaughterHouseVo>> findByUnCheckedAndKeyWord(@RequestParam(value = "keyWord", required = false) String keyWord,
                                                                           @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (null == keyWord) {
            return findByUnChecked(current, size);
        }
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> houseVoIPage = slaughterHouseService.findByUnCheckedAndKeyWord(keyWord, page);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS, houseVoIPage);
    }


    @Deprecated
    @ApiOperation(value = "查询所有已通过审核发布的数据")
    @GetMapping("/findAllOnPermission")
    public CommonResult<List<SlaughterHouseVo>> findAllOnPermission() {
        List<SlaughterHouseVo> list = slaughterHouseService.findAllOnPermission();
        return new CommonResult<List<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @ApiOperation(value = "查询所有已通过审核发布的数据", notes = "分页")
    @GetMapping("/findAllOnPermissionAndPagination")
    public CommonResult<IPage<SlaughterHouseVo>> findAllOnPermissionAndPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                                  @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> housePage = slaughterHouseService.findAllOnMultiStatus(page, 1);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), housePage);
    }

    @Deprecated
    @ApiOperation(value = "查询所有待审核发布数据")
    @GetMapping("/findAllOnPermissionAudit")
    public CommonResult<List<SlaughterHouseVo>> findAllOnPermissionAudit() {
        List<SlaughterHouseVo> list = slaughterHouseService.findAllOnPermissionAudit();
        return new CommonResult<List<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @Deprecated
    @ApiOperation(value = "查询所有待审核发布数据", notes = "分页")
    @GetMapping("/findAllOnPermissionAuditAndPagination")
    public CommonResult<IPage<SlaughterHouseVo>> findAllOnPermissionAuditAndPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                                       @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> housePage = slaughterHouseService.findAllOnMultiStatus(page, 2);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), housePage);
    }

    @Deprecated
    @ApiOperation(value = "查询所有待审核删除数据")
    @GetMapping("/findAllOnDeletionAudit")
    public CommonResult<List<SlaughterHouseVo>> findAllOnDeletionAudit() {
        List<SlaughterHouseVo> list = slaughterHouseService.findAllOnDeletionAudit();
        return new CommonResult<List<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
    }

    @Deprecated
    @GetMapping("/findAllOnDeletionAuditAndPagination")
    @ApiOperation(value = "查询待审核删除的数据", notes = "分页")
    public CommonResult<IPage<SlaughterHouseVo>> findAllOnDeletionAuditAndPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                                     @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> housePage = slaughterHouseService.findAllOnMultiStatus(page, 3);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), housePage);
    }

    @ApiOperation("根据ID查询任意状态的数据（用于编辑/修改）")
    @GetMapping("/findById/{id}")
    public CommonResult<SlaughterHouse> findById(@PathVariable String id) {
        SlaughterHouse byId = slaughterHouseService.getById(id);
        return new CommonResult<SlaughterHouse>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), byId);
    }

    @GetMapping("/findVoById/{id}")
    @ApiOperation(value = "根据屠宰场ID查询任意状态的数据（用于明细）")
    public CommonResult<SlaughterHouseVo> findVoById(@PathVariable(value = "id") String id) {
        SlaughterHouseVo house = slaughterHouseService.findVoById(id);
        return new CommonResult<SlaughterHouseVo>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), house);
    }


    @GetMapping("/findAllVoOnPaginationAndPermission")
    @ApiOperation(value = "查询已通过审核的数据", notes = "分页")
    public CommonResult<IPage<SlaughterHouseVo>> findAllVoOnPaginationAndPermission(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                                    @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> housePage = slaughterHouseService.findAllVoOnPaginationAndPermission(page);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), housePage);
    }

    @GetMapping("/findAlikeOnPaginationAndPermission")
    @ApiOperation(value = "模糊查询已通过审核的数据", notes = "分页")
    public CommonResult<IPage<SlaughterHouseVo>> findAlikeOnPAP(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "keyWord", required = false) String keyWord) {
        if (null == keyWord) {
            return findAllVoOnPaginationAndPermission(current, size);
        } else {
            Page<SlaughterHouseVo> page = new Page<>(current, size);
            IPage<SlaughterHouseVo> housePage = slaughterHouseService.findAlikeOnPAP(page, keyWord);
            return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), housePage);
        }
    }

    @GetMapping("/findVoByNameAndPagination")
    @ApiOperation(value = "根据屠宰场名称模糊查询", notes = "分页")
    public CommonResult<IPage<SlaughterHouseVo>> findVoByNameAndPagination(@RequestParam(value = "slaughterHouseName", required = false) String keyWord,
                                                                           @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (null == keyWord) {
            return findAllVoOnPaginationAndPermission(current, size);
        }
        Page<SlaughterHouseVo> page = new Page<>(current, size);
        IPage<SlaughterHouseVo> houses = slaughterHouseService.findVoByNameAndP(page, keyWord);
        return new CommonResult<IPage<SlaughterHouseVo>>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), houses);
    }

    @GetMapping("/map")
    @ApiOperation(value = "查询所有屠宰场的名字和id")
    public CommonResult getAllSlaughterMapVo(){
        List<SlaughterHouseMapVo> allSlaughterHouseMapVo = slaughterHouseService.getAllSlaughterHouseMapVo();
        if (allSlaughterHouseMapVo.isEmpty()){
            return CommonResult.error("查询结果为空");
        }else {
            return CommonResult.success("查询成功").data(allSlaughterHouseMapVo);
        }
    }

    @GetMapping("/address")
    @ApiOperation(value = "查询所有屠宰场的分布情况")
    public CommonResult getAllSlaughterAddressVo(){
        List<SlaughterHouseAddressVo> list = slaughterHouseService.selectSlaughterHouseAddressVo();
        if (list.isEmpty()){
            return CommonResult.error("查询结果为空");
        }else {
            return CommonResult.success("查询成功").data(list);
        }
    }

}

